package com.fingard.dsp.bank.directbank.bozz02;

import java.math.BigDecimal;
import java.util.*;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.net.ConnState;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class BOZZ02Base extends DirectBase {

    /**
	 * 获取交互字符集
	 * 
	 * @return
	 */
	protected String getCharset(){
        return getBankConfig().getCharset("UTF-8");
    }

    protected static String banks="20114";
	
    private static TransIDHelper idHelper = new TransIDHelper(1, 99999);
    
    /**
     * 获取随机数
     * 
     * @return
     */
    protected String getQryTransID() {
        return Format.DateTime12Year2Format.format(new Date()) + idHelper.getNextIDStr();
    }

    /**
     * 写通用报文头部
     * 
     * @param xmlWriter
     * @param header
     */
    protected void writeCommonHead(XmlTextWriter xmlWriter, BOZZ02Header header){
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("Message");
        xmlWriter.writeStartElement("Head");
        xmlWriter.writeElementString("TrsCode",header.trsCode);
        xmlWriter.writeElementString("ERPTrsTimestamp",header.erpTrsTimestamp);
        xmlWriter.writeElementString("ERPJnlNo",header.erpJnlNo);
        xmlWriter.writeEndElement();
    }
    
    /**
     * 数据发送银行
     * 
     * @param pReqStr
     * @param opName
     * @param needLocal
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String pReqStr,String opName,Boolean needLocal,String flagSign) throws Exception{
        WriteBankLogStep2(pReqStr);
        String[] retStr = new String[]{"",""};
        //String signRetStr = pReqStr;

        //signRetStr = URLEncoder.encode(signRetStr,getCharset());

        String tmpAddrUrl = "http://" + bankFront.serverIP + ":" + bankFront.serverPort+"/eb2e/" + opName + ".do?userPassword=" + bankFront.loginPasswd + "&SIGDATA=" +flagSign;
        if(needLocal){
            tmpAddrUrl += "&_locale=zh_CN";
        }

        //String sendInfo = pReqStr;
        
        byte[] tmpUpBytes = pReqStr.getBytes(getCharset());
        retStr = uploadBytes(tmpAddrUrl, tmpUpBytes);

        if(ConnState.FAIL.equals(retStr[0]) || (retStr[1]!=null && retStr[1].contains("Connection reset"))){
    		if("7516".equals(reqHeader.transType) || "7515".equals(reqHeader.transType) || "7506".equals(reqHeader.transType)){
    			WriteBankLogLn("提交出现异常，等待500毫秒后，重试一次提交");
    			Thread.sleep(500);//如果是余额明细类查询，再尝试一次
        		retStr = uploadBytes(tmpAddrUrl, tmpUpBytes);
    		}
        }

        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
    
    protected String[] sendToBank(String pReqStr,String opName,Boolean needLocal, String fileName, String transCode, String flagSign) throws Exception{
        WriteBankLogStep2(pReqStr);
        String[] retStr = new String[]{"",""};
        //String signRetStr = pReqStr;

        //signRetStr = URLEncoder.encode(signRetStr,getCharset());

        String tmpAddrUrl = "http://" + bankFront.serverIP + ":" + bankFront.serverPort+"/eb2e/" + opName + ".do?userPassword=" + bankFront.loginPasswd +"&SIGDATA=" +flagSign;
        if(needLocal){
            tmpAddrUrl += "&_locale=zh_CN";
        }
        if ("uploadFile".equals(opName)) {
        	tmpAddrUrl += "&fileName=" + fileName + "&delete=0&transCode=" + transCode;
        }
        if ("downloadFile".equals(opName)) {
            tmpAddrUrl=new String("http://" + bankFront.serverIP + ":" + bankFront.serverPort+"/eb2e/" + opName + ".do?userPassword=" + bankFront.loginPasswd);
        	tmpAddrUrl += "&fileName=" + fileName + "&transCode=" + transCode;
        }

        //String sendInfo = pReqStr;
        
        byte[] tmpUpBytes = pReqStr.getBytes(getCharset());
        retStr = uploadBytes(tmpAddrUrl, tmpUpBytes);

        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
    
    private String[] uploadBytes(String pUrl, byte[] pBytes){
    	int timoutMil = this.getReadTimeout(10);
        WriteBankLogLn("2.提交银行的地址：" + pUrl+"，超时时间："+timoutMil+"毫秒");
        WebRequest tmpWebRequest = new WebRequest(pUrl, this.bankFront, this.getSbLog());
        tmpWebRequest.setConnectTimeout(timoutMil);
        tmpWebRequest.setRequestProperty("User-Agent", "API");
        return tmpWebRequest.upload(pBytes, getCharset());
    }

    protected Map<String,ReceiptData> getTransList(Req7516HisTrans p_req7516) throws Exception{
        Map<String,ReceiptData> receiptDataMap=new HashMap<String, ReceiptData>();

        Calendar tmpCalendarFrom = Calendar.getInstance();
        tmpCalendarFrom.setTime(p_req7516.getDateFrom());

        Calendar tmpCalendarTo = Calendar.getInstance();
        tmpCalendarTo.setTime(p_req7516.getDateTo());

        int page=1;//当前页
        int readCount=0;//已查询数
        while (page>0){
            BOZZ02Header tmpBankHeader = new BOZZ02Header();
            tmpBankHeader.trsCode = "B2EActTrsQry";
            tmpBankHeader.erpJnlNo = p_req7516.reqHeader.transSeqID;
            tmpBankHeader.erpTrsTimestamp = Format.DateTimeFormat.format(new Date());
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHead(xmlWriter, tmpBankHeader);
            xmlWriter.writeStartElement("Body");
            xmlWriter.writeElementString("AcNo", p_req7516.actNum);
            xmlWriter.writeElementString("BeginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
            xmlWriter.writeElementString("EndDate", Format.Date8Format.format(tmpCalendarTo.getTime()));
            xmlWriter.writeElementString("PageCount", "50");
            xmlWriter.writeElementString("PageNo", page+"");
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), "B2EActTrsQry", false,"0");
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    if ("000000".equals(tmprspcod)) {
                        int totalCount=Integer.parseInt(tmpBkReader.getFirstTextNotNull("/Message/Body/TotleCount"));
                        while (tmpBkReader.read("/Message/Body/List/Map")) {
                            String jnlNo=tmpBkReader.readedXElement.getSingleText("JnlNo");
                            if(StringHelper.hasAnyChar(jnlNo)){
                                //填充电子回单信息
                                ReceiptData eachData = new ReceiptData();
                                /**本方账号*/
                                eachData.ownAct=tmpBkReader.readedXElement.getSingleText("PayerAcNo");
                                /**对方账号*/
                                eachData.oppActNum=tmpBkReader.readedXElement.getSingleText("PayeeAcNo");
                                /**对方户名*/
                                eachData.oppActName=tmpBkReader.readedXElement.getSingleText("PayeeAcName");
                                String cdFlag = tmpBkReader.readedXElement.getSingleText("DCFlag");
                                String tranAmt = tmpBkReader.readedXElement.getSingleText("Amount");
                                if(tranAmt.contains("-")){
                                    if("D".equals(cdFlag)){
                                        /**交易方向*/
                                        eachData.moneyWay="2";
                                    }else if("C".equals(cdFlag)){
                                        eachData.moneyWay="1";
                                    }
                                    /**金额*/
                                    eachData.amount=new BigDecimal(tranAmt.replaceAll("-",""));
                                }else {
                                    if("D".equals(cdFlag)){
                                        eachData.moneyWay="1";
                                    }else if("C".equals(cdFlag)){
                                        eachData.moneyWay="2";
                                    }
                                    eachData.amount=new BigDecimal(tranAmt);
                                }
                                /**币种*/
                                eachData.cur=convertCurToATS(tmpBkReader.readedXElement.getSingleText("CurrencyCode"));
                                /**金额*/
                                eachData.amount=new BigDecimal(tmpBkReader.readedXElement.getSingleText("Amount"));
                                /**用途*/
                                eachData.purpose=tmpBkReader.readedXElement.getSingleText("Remark");
                                receiptDataMap.put(jnlNo,eachData);
                            }
                            readCount++;
                        }
                        if(totalCount>readCount){
                            page++;
                        }else {
                            page=0;
                        }
                    }else {
                        break;
                    }
                }else {
                    break;
                }
            }else {
                break;
            }
        }
        return receiptDataMap;
    }
}
